from tinydb import TinyDB
from singleton_decorator import singleton
import os, logging

# 数据库管理器
@singleton
class DatabaseManager:
    def __init__(self, db_filename='myVideoHubDatabase.json'):
        """ 初始化数据库管理器 """
        self.db_filename = db_filename
        self.database = None

    def load_database(self):
        """ 加载数据库内容到内存 """
        try:
            logging.info('Loading database.')
            script_dir = os.path.dirname(__file__)
            db_file = os.path.join(script_dir, self.db_filename)
            self.database = TinyDB(db_file)
            logging.info('Database loaded successfully.')
        except Exception as e:
            logging.error(f'Failed to load database: {e}')
            raise
        return self

    def get_database(self):
        return self.database

    def close(self):
        print("关闭数据库")
        self.database.close()